import React from 'react';
import { Navigate } from 'react-router-dom';
import { getUserRole } from '../utils/auth';

interface ProtectedRouteProps {
    children: React.ReactNode;
    allowedRoles?: string[];
}

const ProtectedRoute: React.FC<ProtectedRouteProps> = ({ children, allowedRoles }) => {
    const userRole = getUserRole();

    if (!userRole) {
        // 用户未登录，重定向到登录页面
        return <Navigate to="/login" replace />;
    }

    // Admin can access everything
    if (userRole === 'admin') {
        return <>{children}</>;
    }

    // If user is a 'user' role, all protected routes should be visible but not clickable.
    // The /sp route is not wrapped by ProtectedRoute, so it will remain fully interactive for 'user'.
    if (userRole === 'user') {
        return (
            <div style={{ pointerEvents: 'none' }}>
                {children}
            </div>
        );
    }

    // For any other role (not admin, not user) or if allowedRoles is strictly enforced for non-admin/non-user roles
    // If allowedRoles are specified and the user's role is not in them, redirect to home.
    if (allowedRoles && allowedRoles.length > 0 && !allowedRoles.includes(userRole)) {
        return <Navigate to="/" replace />;
    }

    // Default: allow access if no specific restrictions apply (e.g., if allowedRoles is not set for this route, or userRole is implicitly allowed)
    return <>{children}</>;
};

export default ProtectedRoute;